//
//  ZZCityPickerView.m
//  QMXK
//
//  Created by mry on 2018/4/10.
//  Copyright © 2018年 BeautyFisher. All rights reserved.
//

#import "ZZCityPickerView.h"

#define kHeaderHeight SizeFit(40)
#define kPickViewHeight SizeFit(220)
#define kSureBtnColor [UIColor colorWithRed:147/255.f green:196/255.f blue:246/255.f alpha:1.0]
#define kCancleBtnColor [UIColor colorWithRed:120/255.f green:120/255.f blue:120/255.f alpha:1.0]
#define kHeaderViewColor [UIColor cyanColor]
#define UIColorFromRGBAlph(rgbValue,alpah) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:alpah]
#define KScreenW [UIScreen mainScreen].bounds.size.width
#define KScreenH [UIScreen mainScreen].bounds.size.height
#define SizeFit(size)   (int)(size * KScreenW / 375.0)

#define ISVersion9 [[UIApplication sharedApplication].version float] < 9.0
#ifdef ISVersion9
#define KNFont(s) [UIFont systemFontOfSize:s]
#else
#define KNFont(s) [UIFont fontWithName:@"PingFangSC-Regular" size:s]
//#define KNFont(s) [UIFont fontWithName:@"MicrosoftYaHei" size:s]
#endif

#define iPhoneX \
^(){ \
BOOL iphoneX = NO; \
if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) { \
return iphoneX;\
} \
\
if (@available(iOS 11.0, *)) { \
UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];\
if (mainWindow.safeAreaInsets.bottom > 0.0) { \
iphoneX = YES;\
}\
}\
return iphoneX; \
}()
#define IPhoneXDise (iPhoneX ? 34.f : 0.f)
#define KMainGray UIColorFromRGBAlph(0x999999, 1)
#define KMaincolor UIColorFromRGBAlph(0xFFB21A, 1)

@interface ZZCityPickerView()<UIPickerViewDataSource,UIPickerViewDelegate>

@property (strong, nonatomic)NSArray *provinceData;
@property (assign, nonatomic)NSInteger provinceIndex;
@property (strong, nonatomic)NSDictionary *cityInfo;

@end

@implementation ZZCityPickerView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self loadData];
        [self setUI];
    }
    return self;
}

- (void)loadData{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
    NSString *fileString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    
    NSDictionary *cityInfo = [self dictionaryWithJsonString:fileString];
    if (!cityInfo) {
        return;
    }
    
    self.cityInfo = cityInfo;
    self.provinceData = self.cityInfo[@"provinces"];
}

#pragma mark - 解析json
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData  * jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError * error;
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&error];
    if(error) {
        return nil;
    }
    return dic;
}


- (void)setUI{
    
    [self setBackgroundColor:UIColorFromRGBAlph(0x000000, 0.5)];
    CGFloat h = SizeFit(210) + IPhoneXDise;
    CGFloat y = KScreenH - h;
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, y, KScreenW, h)];
    topView.backgroundColor = [UIColor whiteColor];
    [self addSubview:topView];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, y, KScreenW, SizeFit(40))];
    headView.backgroundColor = UIColorFromRGBAlph(0xFFDFA0, 1);
    [self addSubview:headView];

    UIButton *clostBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, y, SizeFit(80), SizeFit(40))];
    clostBtn.titleLabel.font = KNFont(SizeFit(18));
    [clostBtn setTitle:@"取消" forState:UIControlStateNormal];
    [clostBtn setTitle:@"取消" forState:UIControlStateSelected];
    [clostBtn setTitleColor: UIColorFromRGBAlph(0x333333, 1)  forState:UIControlStateSelected];
    [clostBtn setTitleColor: UIColorFromRGBAlph(0x333333, 1)  forState:UIControlStateNormal];
    [self addSubview:clostBtn];
    
    
    CGFloat x0 = KScreenW - SizeFit(80);
    UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(x0, y, SizeFit(80), SizeFit(40))];
    [self addSubview:sureBtn];
    sureBtn.titleLabel.font = KNFont(SizeFit(18));
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitle:@"确定" forState:UIControlStateSelected];
    [sureBtn setTitleColor: KMaincolor  forState:UIControlStateSelected];
    [sureBtn setTitleColor: KMaincolor  forState:UIControlStateNormal];
    
    [clostBtn addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [sureBtn addTarget:self action:@selector(sureACtion:) forControlEvents:UIControlEventTouchUpInside];
    
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SizeFit(40), KScreenW, h - SizeFit(40))];
    [self.pickerView setBackgroundColor:[UIColor whiteColor]];
    [topView addSubview:self.pickerView];
    
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    
    [self.pickerView reloadComponent:0];
    [self.pickerView reloadComponent:1];
    NSLog(@"");
}

- (void)cancelAction:(UIButton *)btn{
    [self removeFromSuperview];
}

- (void)sureACtion:(UIButton *)btn{
    NSArray *arr = [self getChooseCityArr];
    //滚动太快点击确定取消数据选择
    if(arr.count == 0){
        return;
    }
    
    if (self.completeBlcok != nil) {
        self.completeBlcok(arr);
    }
    [self removeFromSuperview];
}

#pragma mark - Tool
-(NSArray *)getChooseCityArr{
    NSInteger p = [self.pickerView selectedRowInComponent:0];
    NSInteger c = [self.pickerView selectedRowInComponent:1];
    NSDictionary *info = self.provinceData[p];
    NSArray *city = info[@"citys"];
    if(c > (city.count - 1)){
        return @[];
    }
    return @[info[@"name"], city[c]];
}

#pragma mark - PickerView的数据源方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        //返回省个数
        return self.provinceData.count;
    }
    
    if (component == 1) {
        
        NSDictionary *info = self.provinceData[self.provinceIndex];
        NSArray *data = info[@"citys"];
        return data.count;
    }
    
    return 0;
}

#pragma mark - PickerView的代理方法
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *showTitleValue=@"";
    if (component==0){//省
        NSDictionary *info = self.provinceData[row];
        showTitleValue = info[@"name"];
    }
    if (component==1){//市
        NSDictionary *info = self.provinceData[self.provinceIndex];
        NSArray *data = info[@"citys"];
        showTitleValue = data[row];
    }
    return showTitleValue;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view {
    
    for(UIView *singleLine in pickerView.subviews)
        
    {
        
        if (singleLine.frame.size.height < 1)
            
        {
            singleLine.backgroundColor = KMainGray;
            
        }
        
    }
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ([UIScreen mainScreen].bounds.size.width - 30) / 3,45)];
    label.textAlignment=NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:16];
    label.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return label;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 45;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if(component == 0){
        self.provinceIndex = row;
        self.userInteractionEnabled = NO;
        [pickerView reloadComponent:1];
        [pickerView selectedRowInComponent:0];
        self.userInteractionEnabled = YES;
    }
}

+ (ZZCityPickerView *)showPickViewWithComplete:(ZZCityBlock)block superView:(UIView *)superView{
    
    CGFloat screenWitdth = [[UIScreen mainScreen] bounds].size.width;
    CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height;
    
    ZZCityPickerView *pickView= [[ZZCityPickerView alloc] initWithFrame:CGRectMake(0, 0, screenWitdth, screenHeight)];
    
//    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
//    [keyWindow addSubview:pickView];
    [superView addSubview:pickView];
    pickView.completeBlcok = block;
    
    return pickView;
}

+ (ZZCityPickerView *)showPickViewWithProvince:(NSString *)province city:(NSString *)city  complete:(ZZCityBlock)block superView:(UIView *)superView{
    
    ZZCityPickerView *picker = [ZZCityPickerView showPickViewWithComplete:block superView:superView];
    
    [picker scrollToProvince:province city:city];
    
    return picker;
}

- (void)scrollToProvince:(NSString *)province city:(NSString *)city{
    
    if(province.length == 0){
        self.provinceIndex = 0;
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
        [self.pickerView reloadComponent:1];
    }
    else{
        
        for(int i=0; i< self.provinceData.count; i++){
            NSDictionary *dict = self.provinceData[i];
            NSString *name = dict[@"name"];
            if([name isEqualToString:province]){
                self.provinceIndex = i;
                break;
            }
        }
        
        NSDictionary *cityInfo = self.provinceData[self.provinceIndex];
        NSArray *citys = cityInfo[@"citys"];
        NSInteger cityIndex = 0;
        for(int i=0; i<citys.count; i++){
            NSString *city1 = citys[i];
            if([city1 isEqual: city]){
                cityIndex = i;
                break;
            }
        }
        
        [self.pickerView reloadComponent:0];
        [self.pickerView selectRow:self.provinceIndex inComponent:0 animated:NO];
        [self.pickerView reloadComponent:1];
        [self.pickerView selectRow:cityIndex inComponent:1 animated:NO];
    }
}

@end
